package com.qire.manhua.activity;

import android.Manifest;
import android.os.Bundle;
import android.view.View;

import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qire.common.function.Consumer;
import com.qire.common.inject.EventControllerInjector;
import com.qire.common.inject.ViewModelInjector;
import com.qire.common.support.base.BaseActivity;
import com.qire.common.constant.Navigation;
import com.qire.common.utils.FileManager;
import com.qire.common.utils.PermissionsChecker;
import com.qire.common.utils.PermissionsChecker.ObtainWay;
import com.qire.manhua.R;
import com.qire.manhua.controller.ImagePickerController;
import com.qire.manhua.databinding.ActivityImagePickerBinding;
import com.qire.manhua.model.entity.ImageFolder;
import com.qire.manhua.model.viewModel.impl.ImagePickerViewModel;
import com.qire.manhua.model.viewModel.impl.ImagePickerViewModel.AlbumListItemModel;
import com.qire.antscore.annotation.RouteMapping;
import com.qire.antsrouter.inject.Autowired;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 图片选择
 */
@RouteMapping(path = Navigation.Page.ImagePickerPage)
public class ImagePickerActivity extends BaseActivity<ActivityImagePickerBinding> {

    @Autowired(injector = ViewModelInjector.class)
    ImagePickerViewModel viewModel;
    @Autowired(injector = EventControllerInjector.class)
    ImagePickerController controller;

    @Autowired
    Consumer<ArrayList<String>> pickerImageListener; //选择图片监听器
    @Autowired
    int maxCount = 9;

    @Override
    public int layoutRid() {
        return R.layout.activity_image_picker;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel.onAddition(controller, maxCount);
        controller.onAddition(viewModel);

        final String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        new PermissionsChecker(this, this::onAuthorize)
                .setPermissionTips("请允许奇热漫画获取您的文件读写权限，若禁止，将无法使用和上传图片信息。")
                .setPermissionDenyTip("请允许奇热漫画获取您的文件读写权限，若禁止，将无法使用和上传图片信息。\n请在【设置-应用-奇热漫画-权限】中打开相关权限，以正常使用奇热漫画功能")
                .applyPermissions(PERMISSIONS);
    }

    @Override
    public void finish() {
        super.finish();
        pickerImageListener = null;
    }

    private void onAuthorize(ObtainWay obtainWay) {
        initData();
        initListener();
    }

    private void initData() {

        viewModel.updateChooseHintText();

        viewModel.imageAll.setDir("/所有图片");
        viewModel.mDirPaths.add(viewModel.imageAll);
        FileManager.queryImages(this, viewModel::fillImage);

        viewModel.setCurrentImageFolder(viewModel.imageAll);

        int dirPathsSize = viewModel.mDirPaths.size();
        for(int index=0;index < dirPathsSize; index++ ) {
            ImageFolder folder = viewModel.mDirPaths.get(index);
            String titleName = folder.getName() + " (" + folder.images.size() + ")";
            int bottomLineShow = index != dirPathsSize - 1 ? View.VISIBLE : View.GONE;
            int chooseShow = viewModel.getCurrentImageFolder() == folder ? View.VISIBLE : View.GONE;

            viewModel.folderDataList.add(new AlbumListItemModel("file://" + folder.getFirstImagePath(), titleName, bottomLineShow,chooseShow));
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        viewDataBinder().picSelectRv.setLayoutManager(linearLayoutManager);

        viewModel.folderAdapter.notifyDataSetChanged();
        viewModel.selectAdapter.notifyDataSetChanged();
    }

    private void initListener() {
        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;//删除
                int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;//拖拽改变顺序
                return makeMovementFlags(swipeFlags, dragFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                Collections.swap(viewModel.selectDataList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
                viewModel.selectAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                viewModel.removeSelectBitmapItem(viewHolder.getAdapterPosition());
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }
        });
        helper.attachToRecyclerView(viewDataBinder().picSelectRv);

    }

    public void notifyResultsToParent(ArrayList<String> pickerPathList) {
        if(pickerImageListener != null) {
            pickerImageListener.accept(pickerPathList);
        }
        finish();
    }

}